<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/10/28
 * Time: 15:13
 */

namespace app\adminapiv3\service\platform_manage\account;


use app\adminapiv3\model\ServerHostGroupModel;
use app\adminapiv3\service\BaseService;
use app\adminapiv3\service\Password;
use think\Db;
use think\Exception;

class ServerUserService extends BaseService
{
    /**
     * @name 列表
     * @param $params
     * @return array
     * @author wx
     * @date 2019/10/28 15:43
     */
    public function list($params)
    {
        $server = new \app\common\service\platform_manage\account\ServerUserService();
        $list = $server->list($params);
        //处理列表数据
        foreach ($list['data'] as $k => $v){
            $v['ctime'] = date('Y-m-d H:i:s',$v['ctime']);
            if($v['last_login_time']){
                $v['last_login_time'] = date('Y-m-d H:i:s',$v['last_login_time']);
            }else{
                $v['last_login_time'] = '暂无最近登录时间';
            }
            if(!$v['last_login_ip']){
                $v['last_login_ip'] = '暂无上次登录IP';
            }

            $list['data'][$k] = $v;
        }

        //所有资产组数据,用于筛选
        $hostGroupModel = new ServerHostGroupModel();
        $list['search']['hostGroupList'] = $hostGroupModel->getAllList('id,name');
        return $list;
    }

    /**
     * @name 添加
     * @param $addData
     * @return bool
     * @author wx
     * @date 2019/10/28 15:50
     */
    public function add($addData)
    {
        //记录操作日志
        global $logArray;
        $logArray = array(
            'content' => '添加用户',
        );

        //检查重复
        if ($this->checkExist(['real_name' => $addData['real_name']])) {
            $this->setError($this->CODE_FAIL, '请勿添加重复账号');
            return false;
        }

        //资产组必须存在
        $hostGroupModel = new ServerHostGroupModel();
        if (!$hostGroupModel->checkHostGroupExists($addData['host_group_id'])) {
            $this->setError($this->CODE_FAIL, '该资产组不存在,请刷新页面后重新添加');
            return false;
        }

        //单个角色 也作为数组来处理
        $addData['group_id'] = is_array($addData['group_id']) ? $addData['group_id'] : [$addData['group_id']];
        //检查角色id合法性
        if(!\model('ServerUserGroup')->checkGroupId($addData['group_id'])){
            $this->setError($this->CODE_FAIL, '该角色不存在,请刷新页面');
            return false;
        }

        //补充字段
        $addData['reg_ip'] = $_SERVER['REMOTE_ADDR'];
        $addData['last_login_ip'] = '';
        $addData['last_login_time'] = '';
        $addData['ctime'] = time();
        $addData['level'] = 2;
        $addData['salt'] = createSalt(6);

        $serverPassword = new Password();
        $addData['password'] = $serverPassword->encrypt($addData['password'], $addData['salt']);

        Db::startTrans();
        try{
            //用户表数据
            $id = Db::name('server_user')->field(true)->insertGetId($addData);
            if(!$id){
                Db::rollback();
                $this->setError($this->CODE_FAIL, '添加失败');
                return false;
            }

            //用户-角色中间表数据
            $userRole = [];
            foreach ($addData['group_id'] as $key => $item){
                $userRole[] = [
                    'user_id' => $id,
                    'group_id' => $item
                ];
            }

            if (!\model('ServerUserGroupMapping')->insertAll($userRole)) {
                Db::rollback();
                $this->setError($this->CODE_FAIL, '添加失败');
                return false;
            }

            Db::commit();
            $logArray['new_info'] = "用户名：{$addData['real_name']}；用户昵称：{$addData['show_name']}";
            return true;
        }catch (Exception $e){
            Db::rollback();
            $this->setError($this->CODE_FAIL, '添加失败');
            return false;
        }
    }

    /**
     * 修改后台用户
    */
    public function modify($updateData)
    {
        //记录操作日志
        global $logArray;
        $logArray = array(
            'content' => '修改用户',
        );
        $info = Db::name('server_user')->alias('u')
            ->leftJoin('server_host_group g','g.id=u.host_group_id')
            ->where('u.id',$updateData['id'])
            ->field('u.*,g.name as host_group_name')
            ->find();
        if(!$info){
            $this->setError($this->CODE_FAIL,'用户不存在');
            return false;
        }
        //新的资产组必须存在
        $hostGroupModel = new ServerHostGroupModel();
        $result = $hostGroupModel->checkHostGroupExists($updateData['host_group_id']);
        if (!$result) {
            $this->setError($this->CODE_FAIL, '该资产组不存在,请刷新页面后重新添加');
            return false;
        }

        $server = new \app\common\service\platform_manage\account\ServerUserService();
        $server->modify(['id' => $updateData['id']], $updateData);

        $logArray['old_info'] = '用户昵称：' .$info['show_name'] . '邮箱：' . $info['email'] . '资产组：' . $info['host_group_name'];
        $logArray['new_info'] = '用户昵称：' .$updateData['show_name'] . '邮箱：' . $updateData['email'] . '资产组：' . $result['name'];;
        return true;
    }

    /**
     * 删除后台用户
    */
    public function del($id)
    {
        global $logArray;
        $logArray = array(
            'content' => '删除用户',
        );

        $server = new \app\common\service\platform_manage\account\ServerUserService();
        //超管不能删除
        $where[] = array('id', 'in', $id);
        $where[] = array('level', '=', '1');

        if ($this->checkExist($where)) {
            $this->setError($this->CODE_FAIL,'超级管理员不能删除!');
            return false;
        }

        $condition[] = array('id', 'in', $id);

        //查询用户信息
        $list = Db::name('server_user')->where('id','in',$id)->column('real_name');

        Db::startTrans();
        try{
            //删除用户表
            if(!$server->del($condition)){
                Db::rollback();
                $this->setError($this->CODE_FAIL,'删除失败');
                return false;
            }
            //删除 后台 用户-角色 中间表
            Db::name('server_user_group_mapping')->where('user_id','in',$id)->delete();
            Db::commit();

            //记录操作日志
            $logArray['old_info'] = '一共删除'.count($list).'个用户；用户名称为'.implode('，',$list);
            return true;
        }catch (Exception $e){
            Db::rollback();
            $this->setError($this->CODE_FAIL,'删除失败');
            return false;
        }
    }

    /**
     * @name 修改当前用户密码
     * @author wx
     * @date 2019/10/28 16:12
     */
    public function modifyUserPassword($oldPassword, $newPassword)
    {
        global $logArray;
        $logArray = array(
            'content' => '修改当前登录用户密码',
        );

        $user_info = $this->getLoginUserInfo();
        $where['id'] = $user_info['id'];
        $server = new \app\common\service\platform_manage\account\ServerUserService();
        $user = $server->findData($where);
        if (!$user) {
            $this->setError($this->CODE_FAIL, '该用户不存在');
            return false;
        }

        //验证旧密码是否正确
        $serverPassword = new Password();
        $checkRes = $serverPassword->decrypt($oldPassword, $user['salt'], $user['password']);
        if (!$checkRes) {
            $this->setError($this->CODE_FAIL, '当前密码不正确');
            return false;
        }

        //修改用户信息
        $updateData['password'] = $serverPassword->encrypt($newPassword, $user['salt']);
        $server->modify(['id' => $user_info['id']], $updateData);

        return true;
    }

    /**
     * @name 验证是否存在
     * @param $condition
     * @author wx
     * @date 2019/10/28 16:20
     */
    public function checkExist($condition)
    {
        $server = new \app\common\service\platform_manage\account\ServerUserService();
        $info = $server->findData($condition);

        if(!$info){
            return false;
        }
        return true;
    }

    /**
     * @name 修改超级管理员密码
     * @param $password
     * @return bool
     * @author wx
     * @date 2019/12/23 10:19
     */
    public function modifyAdmin($password)
    {
        //记录操作日志
        global $logArray;
        $logArray = array(
            'content' => '修改超级管理员密码',
        );
        $userInfo = $this->getUserInfo();

        if($userInfo['level'] != 0){
            $this->setError($this->CODE_FAIL, '您没有权限执行此操作');
            return false;
        }

        $serverPassword = new Password();
        $updateData['salt'] = createSalt(6);
        $updateData['password'] = $serverPassword->encrypt($password, $updateData['salt']);

        $server = new \app\common\service\platform_manage\account\ServerUserService();
        $server->modify(['level' => 1], $updateData);

        return true;
    }


}